<?php
/**
 * Created by PhpStorm.
 * User: kkw
 * Date: 2019/1/29
 * Time: 21:43
 */

namespace kkw\user;


use kkw\user\table\UserTable;
use suda\core\Request;
use suda\core\Response;

class Util
{
    public static function printHeader() {
        Response::addHeader('Access-Control-Allow-Origin','*');
        Response::addHeader('Access-Control-Allow-Method','GET,POST');
        Response::addHeader('Access-Control-Allow-Headers','Content-Type,user-token,user-id');
        Response::addHeader('Access-Control-Expose-Headers','user-token,user-id');
//        Response::addHeader('Access-Control-Allow-Credentials','true');
    }

    public static function getUserId() {
        $user = new UserTable();
        $id = Request::getHeader('user-id');
        $token = Request::getHeader('user-token');
        if ($user->select('*', ['id' => $id, 'token' => $token])->fetch()) {
            return $id;
        }
        return 0;
    }


    public static function userSign(int $id) {
        $token = md5(microtime(true));
        $user = new UserTable();
        $user->updateByPrimaryKey($id, [
            'token' => $token,
        ]);
        Response::addHeader('user-token', $token);
        Response::addHeader('user-id', $id);
        return $token;
    }
}